package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    @Scheduled(cron = "0 0/1 * * * ? ")
    @Transactional
    public void processOutTimeOrder(){
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //查询数据库中订单数据 条件： 状态-待付款 ，下单时间< 当前时间-15分钟
       List<Orders> ordersList =  ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT , time);
        //查询到了数据，代表存在超时未支付订单，需要修改订单状态status=6，取消订单 ，update
       if(ordersList != null && ordersList.size() > 0){
           ordersList.forEach(order -> {
               order.setStatus(Orders.CANCELLED);
               order.setOrderTime(LocalDateTime.now());
               order.setCancelReason("支付超时");
               ordersMapper.update(order);

           });
       }

    }
    @Scheduled(cron = " 0 0 1 * * ? ")
//    @Scheduled(cron = " 0 52 20 * * ? ") //TODO:测试用
    @Transactional
    public void processDeliveryOrder(){
        log.info("开始处理处于配送中的订单");
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        //查询数据库中订单数据 条件:状态-配送中 ，下单时间 < 当前时间-1小时
        List<Orders> orders = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        //查询到了数据，代表存在一直派送的订单，需要修改订单状态为5，完成订单
        if(orders != null && orders.size() > 0){
            orders.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
                ordersMapper.update(order);
            });
        }
    }
}
